<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<link href="../../component/layui/css/layui.css" rel="stylesheet" />
	<link href="../../admin/css/pearCommon.css" rel="stylesheet" />
</head>
<body>
<body class="pear-container">
<div class="layui-card">
	<div class="layui-card-body">
		<form action="" class="layui-form">
			<div class="layui-form-item">
				<label class="layui-form-label">场景名称</label>
				<div class="layui-input-inline">
					<input class="layui-input" id="demoReload"  name="sceneName" placeholder="" type="text">
				</div>
				<!--		                    <label class="layui-form-label">要素格式</label>
                                            <div class="layui-input-inline">
                                                <input type="text" name="username" placeholder="" class="layui-input">
                                            </div>-->
				<a class="pear-btn pear-btn-md pear-btn-primary" id="sceneSearch" lay-filter="user-query" lay-submit>
					<i class="layui-icon layui-icon-search"></i>
					查询
				</a>
				<button class="pear-btn pear-btn-md" type="button" id="sceneReset">
					<i class="layui-icon layui-icon-refresh"></i>
					重置
				</button>
			</div>
		</form>
	</div>
</div>
<div class="layui-card">
	<div class="layui-card-body">
		<table id="user-table" lay-filter="user-table"></table>
	</div>
</div>
</body>
<div class="site-text" id="scene-window" style="margin: 5%; display: none"  target="test123">
	<form class="layui-form" id="scene-add">
		<div class="layui-form-item">
			<label class="layui-form-label">场景名称</label>
			<div class="layui-input-block">
				<input autocomplete="off" class="layui-input" id="sceneName" lay-verify="required"  name="title" placeholder="请输入" maxlength="50" required type="text">
				<div class="layui-form-mid layui-word-aux" id="inputSceneName">必填项</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">场景描述</label>
			<div class="layui-input-block">
				<textarea class="layui-textarea" id="remark" maxlength="200" name="desc" placeholder="请输入"></textarea>
			</div>
		</div>
	</form>

</div>
<script id="user-toolbar" type="text/html">
	<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
		<i class="layui-icon layui-icon-add-1"></i>
		创建场景
	</button>
</script>

<script id="user-bar" type="text/html">
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑地图</a>
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>

<!--	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit2">编辑</a>-->

	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="modify">修改</a>

	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!--<script type="text/html" id="userbar">
	<input type="checkbox" name="状态" valueId="{{d.id}}" valueElementName="{{d.elementName}}" valueElementUrl="{{d.elementUrl}}" valueServiceType="{{d.serviceType}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="enabledState" {{ d.status == "1" ? "checked" : "" }}>
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>
	<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>-->
<!--<script id="user-edit" type="text/html">
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
</script>-->

<script id="icon" type="text/html">
	{{#if(d.coverUrl){}}
	<img src="/one/file/preview/url?url={{d.coverUrl}}" alt=""/>
	{{#}else{}}
	<img src="../sceneManage/img/default.jpg" alt="">
	{{#}}}
</script>

<script id="service-status" type="text/html">
	<input type="checkbox" name="状态" valueId="{{d.id}}" valueElementName="{{d.sceneName}}" index="{{d.LAY_TABLE_INDEX}}" lay-skin="switch"  lay-filter="enabledState" {{ d.status == "1" ? "checked" : "" }} >
	{{#if (d.status == 1) { }}
	<span style="color: #338528;">启用</span>
	{{# }else if(d.status == 0){ }}
	<span>禁用</span>
	{{# } }}
</script>
<script id="user-createTime" type="text/html">
	{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}
</script>

<script src="../../component/layui/layui.js"></script>
<script>
	var sceneManageObj = {};
	var dataList=1;
	layui.use(['table','form','jquery'],function () {
		let table = layui.table;
		let form = layui.form;
		let $ = layui.jquery;

		let MODULE_PATH = "/system/user/";

		let cols = [
			[
				// {type:'checkbox'},
				{title: '缩略图', field: 'icon',templet:'#icon',align:'center',width:80},
				// {title: '要素分类', field: 'sex', align:'center', width:100, templet:'#user-sex'},
				{title: '场景名称', field: 'sceneName',sort: false, align:'center'},
				{title: '场景描述', field: 'remark', align:'center'},
				// {title: '场景状态', field: 'enable', align:'center', templet:'#user-enable'},
				{title: '创建时间', field: 'createTime', sort: true,align:'center',templet:'#user-createTime'},
				{title: '更新时间', field: 'updateTime',sort: true, align:'center',templet:'#user-createTime'},
				{title: '场景状态', field: 'status', sort: true,align:'center', templet:'#service-status'},
				// {title: '编辑', field: 'login', align:'center', templet:'#user-edit'},
				{title: '操作', toolbar: '#user-bar', align:'center', width:300}
			]
		];

		table.render({
			elem: '#user-table',
			url: '/one/scene/list',
			method: 'post',
			contentType: 'application/json',
			where: {
				orderDesc: 0,
				order: 3
			},
			request: {
				pageName: 'pageNo' //页码的参数名称，默认：page
				,limitName: 'pageSize' //每页数据量的参数名，默认：limit
			},
			parseData: function(res){ //res 即为原始返回的数据
				dataList=res.data.list;
				return {
					"createTime": null,
					"createBy": null,
					"updateTime": null,
					"updateBy": null,
					"remark": null,
					"code": 200,
					"msg": "...",
					"count": res.data.total,
					"data":res.data.list
				}
			},
			page: true ,
			cols: cols ,
			skin: 'line',
			toolbar: '#user-toolbar',
			even: true,//开启隔行背景
			response: {
				statusCode: 200 //成功的状态码，默认：0
			},
			initSort: {
				field: 'createTime',
				type: 'desc',
			},
			defaultToolbar: [{
				layEvent: 'refresh',
				icon: 'layui-icon-refresh',
				title:'刷新'
			}, 'filter']  //, 'print', 'exports'
		});

		table.on('tool(user-table)', function(obj){
			if(obj.event === 'del'){
				sceneManageObj.del(obj);
			} else if(obj.event === 'edit'){
				sceneManageObj.edit(obj);
			}  else if(obj.event === 'detail'){
				sceneManageObj.detail(obj);
			}else if(obj.event === 'modify'){
				sceneManageObj.modify(obj);
			}
		});

		table.on('toolbar(user-table)', function(obj){
			if(obj.event === 'add'){
				sceneManageObj.add();
			} else if(obj.event === 'refresh'){
				sceneManageObj.refresh();
			} else if(obj.event === 'batchRemove'){
				sceneManageObj.batchRemove(obj);
			} else if(obj.event === 'view'){
				sceneManageObj.view(obj);
			}
		});


		table.on('sort(user-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
			// console.log(obj.field); //当前排序的字段名
			// console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

			var field=obj.field;
			var type=obj.type;
			var order=1;
			var orderDesc=0;
			if(field==='createTime'){
				order=3;
			}else if(field==='updateTime'){
				order=2;
			}

			if(type==="asc"){
				orderDesc=1
			}else if(type=="desc"){
				orderDesc=0;
			}else{
				orderDesc=0;
				order=2;
			}


			//尽管我们的 table 自带排序功能，但并没有请求服务端。
			//有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
			table.reload('user-table', {
				initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
				,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
					order: order //排序字段   在接口作为参数字段  field order
					,orderDesc: orderDesc //排序方式   在接口作为参数字段  field order
				}
			});
		});
		form.on('submit(user-query)', function(data){
			// table.reload('user-table',{where:data.field});
			// return false;
		});
        //创建场景
		sceneManageObj.add = function(){
			$("#scene-add")[0].reset();//重置form
			//放开修改时隐藏的必填项
			$('#inputSceneName').show();
			layer.open({
				type: 1,
				title: '创建场景',
				shade: 0.1,
				area: ['70%', '70%'],
				content: $('#scene-window'),
				resize: true,
				btn: ['进入编辑场景', '取消'],
				success:function(layero,index){
					$('#sceneName').show();
					$('#remark').show();
				},
				yes:function(index,layero){
					if(!$('#sceneName').val()){
						layer.msg("请输入场景名称", {icon: 5});
						return;
					}
					let loading = layer.load();
					$.ajax({
						url: "/one/scene",
						type: "POST",
						data:JSON.stringify({
							sceneName: $('#sceneName').val(),
							remark: $('#remark').val(),
							status: 0
						}),
						dataType: "json",
						contentType: "application/json; charset=UTF-8",
						success: function(result){
							if (result.errorCode === '401') {
								loginStatusIntercept(result.msg)
								return
							}
							layer.close(loading);
							if(result.success){
								layer.alert('创建成功',{icon:1,title:'提示'},function(i){
									layer.close(i);
									layer.close(index);//关闭弹出层
									$("#scene-add")[0].reset();//重置form
									// var jumpSceneId=result.data.id;//获取当前行的id传给sceneConfig页面
									var JUMP_PATH = window.sessionStorage.envLocation+"/view/sceneManage/sceneConfig.html?sceneId="+result.data.id;

									window.open(JUMP_PATH);
								});
								table.reload('user-table',{//重载表格
									page:{
										curr:1
									}
								})
							}else{
								layer.msg("添加失败,失败原因:"+result.msg, {icon: 5});
							}
						},
						error:function (err) {
							layer.msg("后台请求出错:"+err.responseText,{icon:2,time:1000});
							layer.close(loading);
						}
					});
				}
			});
		};
		$("#demoReload").unbind("keydown").keydown(function (e) {//当按下按键时
			e.stopPropagation()
			var key = e.keyCode || e.charCode || e.which;
			if (key == 13) {
				e.preventDefault()
				$("#sceneSearch").trigger('click');
			}
        })
		$('#sceneSearch').on('click', function(){

					var demoReload = $('#demoReload');
					//执行重载
					table.reload('user-table', {
						// url:'/back/one/element/origin/list',
						page: {
							curr: 1 //重新从第 1 页开始
						}
						// ,method: 'post'
						,where: {
							sceneName: demoReload.val()
						}
					}, 'data');


		});

		$('#sceneReset').on('click', function(){

					var demoReload = $('#demoReload');
			demoReload.val("")
					//执行重载
					table.reload('user-table', {
						// url:'/back/one/element/origin/list',
						page: {
							curr: 1 //重新从第 1 页开始
						}
						// ,method: 'post'
						,where: {
							sceneName: demoReload.val()
						}
					}, 'data');

		});


		sceneManageObj.edit = function(obj){
			// var editId=obj.data.id;//获取当前行的id传给sceneConfig页面
			var JUMP_PATH = window.sessionStorage.envLocation+"/view/sceneManage/sceneConfig.html?sceneId="+obj.data.id;
			window.open(JUMP_PATH);
		};
		//修改场景
		sceneManageObj.modify = function(obj){
			var data = obj.data;//获得当前行数据
			layer.open({
				type: 1,
				title: '修改场景',
				shade: 0.1,//遮罩透明度
				area: ['60%', '40%'],
				content: $('#scene-window'),
				resize: true,
				btn: ['确定', '取消'],
				success:function(layero,index){
					$('#sceneName').val(data.sceneName);
					$('#remark').val(data.remark);
					$('#inputSceneName').hide();
				},
				yes:function(index,layero){
					if(!$('#sceneName').val()){
						layer.msg("请输入场景名称", {icon: 5});
						return;
					}
					$.ajax({
						url: "/one/scene",
						type: "PUT",
						data:JSON.stringify({
							sceneName: $('#sceneName').val(),
							remark: $('#remark').val(),
							id: data.id,
							status:data.status
						}),
						dataType: "json",
						contentType: "application/json; charset=UTF-8",
						success: function(data){
							if (data.errorCode === '401') {
								loginStatusIntercept(data.msg)
								return
							}
							if(data.errorCode==0){
								layer.msg('修改成功',{icon:1,title:'提示'},function(i){
									layer.close(i);
									layer.close(index);//关闭弹出层
									$('#inputSceneName').show();
									$("#scene-add")[0].reset()//重置form
								});
								table.reload('user-table',{//重载表格
									page:{
										curr:obj.curr
									}
								})
							}else{
								layer.msg("修改失败", {icon: 5});
							}
						}
					});
				}
			});
		};



		sceneManageObj.detail = function(obj){
			// var pathname = top.location.href;
			var JUMP_PATH = window.sessionStorage.envLocation+"/sceneNavigate.html?sceneId="+obj.data.id;
			window.open(JUMP_PATH);
		};
		sceneManageObj.del = function(obj){
			var data = obj.data;//获得当前行数据
			layer.confirm('确认删除该场景吗？', {icon: 3, title:'提示'}, function(index){
				let ids = data.id;
				$.ajax({
					url: "/one/scene"+"?ids="+ids,
					type: "DELETE",
					// data:{ids:ids},
					dataType: "json",
					success: function(data){
						if (data.errorCode === '401') {
							loginStatusIntercept(data.msg)
							return
						}
						if(data.errorCode==0){
							//删除这一行
							obj.del();
							//关闭弹框
							layer.close(index);
							layer.msg("删除成功", {icon: 6});
							table.reload('user-table');
						}else{
							layer.msg("删除失败", {icon: 5});
						}
					}
				});
			});
		};
		form.on('switch(enabledState)', function(obj){
			//获取自定义标签valueId等上的值
			var switch_id = obj.elem.attributes['valueId'].nodeValue;
			var switch_ElementName = obj.elem.attributes['valueElementName'].nodeValue;
			//根据表格每行索引查找要素内容
			// var switch_index = obj.elem.attributes['index'].nodeValue;
			// var switch_remark = dataList[switch_index].remark;
			// var switch_angle = dataList[switch_index].angle;
			// var switch_coverUrl = dataList[switch_index].coverUrl;
			//开关是否开启，true或者false
			var checked = obj.elem.checked;
			var validFlag = Number(obj.elem.checked);//转为 0、1
			$.ajax({
				url: "/one/scene",
				type: "PUT",
				data:JSON.stringify({
					id:switch_id,
					sceneName: switch_ElementName,
					// angle: switch_angle,
					// coverUrl: switch_coverUrl,
					// remark: switch_remark,
					status: validFlag
				}),
				dataType: "json",
				contentType: "application/json; charset=UTF-8",
				success: function(data){
					if (data.errorCode === '401') {
						loginStatusIntercept(data.msg)
						return
					}
					if(data.errorCode==0){
						obj.elem.checked = checked;
						// form.render('checkbox');
						// form.render();
						table.reload('user-table');
						console.log(obj.elem.checked);
						layer.msg('要素状态：'+ (obj.elem.checked ? '启用' : '禁用'), {
							icon : 1
						});
					}else{
						layer.msg(' 失败', {
							icon : 2
						});
					}
				}
			});
			form.render('checkbox');
		});

		sceneManageObj.batchRemove = function(obj){
			let data = table.checkStatus(obj.config.id).data;
			if(data.length === 0){
				layer.msg("未选中数据",{icon:3,time:1000});
				return false;
			}
			let ids = "";
			for(let i = 0;i<data.length;i++){
				ids += data[i].userId+",";
			}
			ids = ids.substr(0,ids.length-1);
			layer.confirm('确定要删除这些用户', {icon: 3, title:'提示'}, function(index){
				layer.close(index);
				let loading = layer.load();
				$.ajax({
					url: MODULE_PATH+"batchRemove/"+ids,
					dataType:'json',
					type:'delete',
					success:function(result){
						layer.close(loading);
						if(result.success){
							layer.msg(result.msg,{icon:1,time:1000},function(){
								table.reload('user-table');
							});
						}else{
							layer.msg(result.msg,{icon:2,time:1000});
						}
					}
				})
			});
		};

		sceneManageObj.refresh = function(param){
			table.reload('user-table');
		}
	})
</script>
</body>
</html>
